package org.sapp;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 * Initialize embedded EclipseLink ( without EJB )
 * Required for using EclipseLink in JavaSE standalone application.
 * Not required for using EclipseLink inside OpenEJB.
 *  
 * @author vitalii
 *
 */

public class EclipseLinkFactory 
{
	private EntityManager em;	
	
	private String unitName;
	
	public EclipseLinkFactory(String unitName)
	{
		this.unitName = unitName; 
	}
	
	public EntityManager getEntityManager()
	{
		return em;
	}
	
	/**
	 * Initialize EclipseLink
	 * 
	 * @throws Exception
	 */
	
	public void init() throws Exception 
	{
		setupEclipseLink();
	}
	
	/**
	 * Initialize database
	 * 
	 */

	protected static void initDB(String dbDriver, String dbHost, int dbPort,
			String dbUserName, String dbPassword, String dbName )  throws Exception  
	{
		String url = "jdbc:"+dbDriver+"://"+dbHost+":"+String.valueOf(dbPort)+"/";
		Connection conn = DriverManager.getConnection(url, dbUserName, dbPassword);
		Statement stmt = conn.createStatement();
		
		// Drop database ( if exist )
		try {
			stmt.executeUpdate("DROP DATABASE "+dbName);
		} catch (Exception e) { /* Ignore this exception */ };
		
		// Create empty database
		stmt.executeUpdate("CREATE DATABASE "+dbName);		
	}	
	
	/**
	 * Loading MySQL JDBC driver
	 * 
	 * @throws Exception
	 */
	
	protected void loadMySQLDriver(String driverClassName)  throws Exception 
	{
		Class.forName(driverClassName);			
	}	
	
	/**
	 * Initialize standalone EclipseLink JPA.
	 * Required for using EclipseLink in JavaSE standalone application.
	 * Not required for using EclipseLink inside OpenEJB. 
	 * 
	 * @throws Exception
	 */
	
	protected void setupEclipseLink() throws Exception 
	{
		PersistencyParameters params = PersistencyParser.parse(unitName);		
		
		//loadMySQLDriver("com.mysql.jdbc.Driver");
		loadMySQLDriver(params.getDBDriverClassName());
				
		initDB(params.getDBDriver(), params.getDBHost(), params.getDBPort(),
				params.getDBUserName(), params.getDBPassword(), params.getDBName());
		
		EntityManagerFactory emf = 
			Persistence.createEntityManagerFactory(
					unitName
				);
		em = emf.createEntityManager();				
	}	

}
